package gateway.server.route;

import gateway.api.annotation.Named;

import java.util.Optional;
import java.util.ServiceLoader;

/**
 * @author Jin Zheng
 * @since 2020-09-13
 */
public class RouteLoader
{
	public RouteLoader()
	{
	}


	public <T> RouteItem<T> load(String name, Class<T> clazz)
	{
		RouteItem<T> item = new RouteItem<>(name);
		Optional<ServiceLoader.Provider<T>> optional = ServiceLoader.load(clazz).stream()
				.filter(p ->
				{
					Named annoNamed = p.type().getAnnotation(Named.class);
					if (annoNamed == null)
						return false;

					item.setType(annoNamed.type());
					item.setAsync(annoNamed.async());
					return annoNamed.value().equals(name);
				}).findFirst();
		if (optional.isEmpty())
			return null;

		item.setTarget(optional.get().get());
		return item;
	}

}
